<template>
  <a-modal
    :visible="visible"
    centered
    destroyOnClose
    title="编辑常用功能"
    :bodyStyle="{ padding: '0 10px' }"
    @cancel="handleCancel"
    @ok="handleOk"
    okText="保存"
    :confirmLoading="submitLoading"
    :width="600"
  >
    <a-tabs v-model:activeKey="currentTab">
      <a-tab-pane :key="1" tab="所有功能">
        <section class="content">
          <a-row :gutter="[0, 24]" v-if="menuList.length">
            <!--   树形数据   -->
            <a-tree
              defaultExpandAll
              :checkedKeys="oftenAppIds"
              :tree-data="menuList"
              checkable
              :fieldNames="{
                key: 'alias',
                title: 'name',
              }"
              @check="handleCheckChange"
            >
            </a-tree>
          </a-row>
          <div v-else class="no-data">无结果</div>
        </section>
      </a-tab-pane>
      <a-tab-pane :key="2" tab="功能排序">
        <section class="content">
          <!-- <a-row :gutter="[0, 24]" v-if="tab2List.length">
            <a-col :span="24" v-for="app of tab2List" :key="app.id"> -->
          <a-alert
            message="拖拽左侧图标进行排序。"
            style="margin-bottom: 20px"
          />
          <draggable
            v-if="oftenAppList.length"
            v-model="oftenAppList"
            group="collect"
            item-key="alias"
            handle=".order-icon"
            @end="dragEnd"
          >
            <template #item="{ element: app }">
              <div class="app-item" style="margin-bottom: 20px">
                <div class="order-icon">
                  <MenuOutlined />
                </div>
                <div class="icon-box">
                  <img class="image" v-if="app.app_logo" :src="app.app_logo" />
                  <cu-icon v-else-if="app.icon" :type="app.icon"></cu-icon>
                  <cu-icon v-else type="org-menu-yingyong"></cu-icon>
                </div>
                <div class="app-name">
                  <div class="name">{{ app.name }}</div>
                  <div v-if="app.app_info" class="nowrap desc">{{ app.app_info }}</div>
                </div>
                <a-button
                  type="primary"
                  ghost
                  danger
                  size="small"
                  @click="removeCollectApp(app)"
                >
                  移除
                </a-button>
              </div>
            </template>
          </draggable>

          <!-- </a-col>
          </a-row> -->
          <a-empty v-else description="您还没有添加常用应用哦~">
            <a-button type="primary" @click="currentTab = 1">去添加</a-button>
          </a-empty>
        </section>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>

<script>
import { message } from "ant-design-vue";
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import request from "@/common/utils/request";
import draggable from "vuedraggable";
import {MenuOutlined, TeamOutlined} from "@ant-design/icons-vue";
import _ from 'lodash';
import store from "@/store/index";

export default defineComponent({
  name: "CustomAppModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    collectList: {
      type: Array,
      default: () => [],
    },
  },
  components: {TeamOutlined, draggable, MenuOutlined },
  setup(props, { emit }) {
    const state = reactive({
      currentTab: 1,
      oftenAppList: [], // 常用应用
      hasDraged: false,
      submitLoading: false,
    });
    const handleCancel = () => {
      emit("close");
    };

    const handleMapList = (list) => {
      list.forEach((item) => {
        if (!item.url) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
        if (item.alias == 'workbench') {
          item.disabled = true;
        }
        if (item?.children?.length) {
          handleMapList(item?.children)
        }
      })
    };

    const menuList = computed(() => {
      let list = _.cloneDeep(store.getters.userMenu.filter((item) => item.hide != true));
      handleMapList(list);
      return list;
    });

    const oftenAppIds = computed(() => {
      return state.oftenAppList.map((item) => item.alias);
    });
    const handleOk = () => {
      state.submitLoading = true;
      request.post("/org", "/app/batch/add", {menu_alias_list: oftenAppIds.value}).then((res) => {
        const result = state.oftenAppList.map((item, index) => ({
          menu_alias: item.alias,
          sort: state.oftenAppList.length - index,
        }));
        request
          .post("/org", "/app/collect/sort", {
            collect_arr: result,
          })
          .then(() => {
            message.success("保存成功！");
            state.submitLoading = false;
            let dataList = _.cloneDeep(result).sort((a, b) => b.sort - a.sort)?.map((item) => item.menu_alias);
            window.microApp.forceDispatch({
              type: "dispatchStore",
              dispatchName: 'SetAppList',
              value: dataList,
            })
          });
        handleCancel();
      })
    };

    const removeCollectApp = (app) => {
      const idx1 = state.oftenAppList.findIndex((item) => item.id == app.id);
      state.oftenAppList.splice(idx1, 1);
    };

    const dragEnd = () => {
      state.hasDraged = true;
    };

    const handleCheckChange = (checkedKeys, e) => {
      state.oftenAppList = e?.checkedNodes || [];
    };


    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.oftenAppList = _.cloneDeep(props.collectList);
        } else {
          state.hasDraged = false;
          state.currentTab = 1;
          state.submitLoading = false;
        }
      }
    );

    return {
      ...toRefs(state),
      oftenAppIds,
      menuList,
      handleCancel,
      handleOk,
      removeCollectApp,
      dragEnd,
      handleCheckChange,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  width: 100%;
  height: 600px;
  overflow: hidden auto;
  padding: 0 20px 20px 20px;
  .app-item {
    width: 100%;
    display: flex;
    align-items: center;
    .order-icon {
      cursor: all-scroll;
      padding-right: 15px;
    }
    .icon-box {
      min-width: 40px;
      max-width: 40px;
      height: 40px;
      overflow: hidden;
      border-radius: @border-radius-base;
      background: @primary-color;
      color: #fff;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      .image {
        width: 100%;
        height: 100%;
      }
    }
    .app-name {
      margin: 0 10px;
      flex: 1;
      overflow: hidden;
      .name {
        color: #333;
        font-weight: 600;
      }
      .desc {
        color: #666;
        font-size: 12px;
      }
    }
    .app-option {
      min-width: 60px;
      max-width: 60px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

:deep(.ant-tabs-nav-wrap) {
  margin-bottom: 16px;
}
</style>
